package command

import "context"

// Command 命令
type Command[Request any,Response any] func(ctx context.Context, request Request) (response Response, err error)

type Middleware[Request any,Response any] func(Command[Request,Response]) Command[Request,Response]

func Chain[Request any,Response any](outer Middleware[Request,Response], others ...Middleware[Request,Response]) Middleware[Request,Response] {
	return func(next Command[Request,Response]) Command[Request,Response] {
		for i := len(others) - 1; i >= 0; i-- { // reverse
			next = others[i](next)
		}
		return outer(next)
	}
}

func Use[Request any,Response any](command Command[Request,Response], middlewares ...Middleware[Request,Response]) Command[Request,Response] {
	var cmd Command[Request,Response]
	cmd = command
	for i:=len(middlewares)-1;i>=0;i--{
		cmd = middlewares[i](cmd)
	}
	return cmd
}